//app.js
const https = require('./utils/https')
// const base = "http://192.168.0.152/xcx"
const base = "https://api.hj-tec.com/xcx"
// const  base = "https://huapi.yyang.xin/xcx"
// const upload = "https://huapi.yyang.xin/api/v1/image"
// const upload = "http://192.168.0.152/api/v1/image"
const upload = "https://api.hj-tec.com/api/v1/image"
// const msg = "http://192.168.0.152/sms/verify-code"
const msg = "https://api.hj-tec.com/sms/verify-code"
// const msg = "https://huapi.yyang.xin/sms/verify-code"
const header = {
    'Accept': 'application/json',
    'content-type': 'application/json',
    'Authorization': null,
}
App({
    onLaunch: function () {
        this.globalData.upload = upload
        this.login()
    },
    login() {
        wx.login({
            success: res => {
                if (res.code) {
                    this.axios('/login','POST', (response)=> {
                        if (response){
                            this.globalData.userToken = response.token
                            // log
                            console.log(response)
                        }
                    },{code:res.code})
                } else {
                    console.log("登录失败" + res.errMsg);
                }
            }
        })
    },
    axios(url, method, cb, params = {}) {
        wx.showLoading({
            title: '加载中',
        })
        if (header.Authorization == '' && url != '/login') {
            this.login()
            return this.axios(url,method,cb,params)
        }else {
            header.Authorization = 'Bearer ' + this.globalData.userToken
        }

        wx.request({
            url: base + url,
            method: method,
            dataType: 'json',
            data: params,
            header: header,
            success: function (res) {
                let response = res.data
                console.log(response)
                wx.hideLoading();
                if (response.code===200){
                    return typeof cb == "function" && cb(response.data)
                }
                if (response.code===401){
                    this.login()
                    return this.axios(url,method,cb,params)
                }
                wx.showModal({
                    title: '错误',
                    content: response.msg,
                    showCancel: false
                })
                return typeof cb == "function" && cb(false)
            },
            fail: res=> {
                console.log(res)
                wx.hideLoading();
                wx.showModal({
                    title: '网络错误',
                    content: '网络出错，请刷新重试',
                    showCancel: false
                })
                return typeof cb == "function" && cb(false)
            }
        })
    },
    // post(url,params){
    //
    // },
    globalData: {
        // userInfo: null,
        request: https.https,
        userToken: '',
        upload: '',
        msg:msg
    }
})
